// stock/bom/bom.js
let listBehavior = require('../../behavior/list')
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {

    tableName: 'Bom',

    list: [], //数据列表

    displayField: [  //显示字段列表
      {field: 'goods_type;value', title: '商品类别'}
      , {field: 'goods_brand;value', title: '品牌'}
      , {field: 'goods_place;value', title: '产地'}
      , {field: 'goods_unit_quantity', title: '数量'}
      , {field: 'goods_unit;value', title: '单位'}
      , {field: 'goods_model;value', title: '规格型号'}
    ],

    keyList: [  //搜索关键字
      {field_id: 'goods_id',field_name: '商品编码'},
      {field_id: 'goods_name',field_name: '商品名称'},
    ],
    sumList: [] //底部统计字段集合
  },
  //明细展开收起
  bindDetailShow(e){
    let {index, row} = e.currentTarget.dataset,
      {list} = this.data;
    if (row.is_loaded){
      this.setData({
        [`list[${index}].is_open`]: !this.data.list[index].is_open
      });
      return
    }
    this.getDetailData(row.row_id,index);
  },
  //删除
  bindDelete(e){
    if (!this.checkAuth('tableDelete')) return;
    let {rid,s_index,p_index} = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确认删除该记录？',
      success: (res) => {
        if(res.confirm) {
          wx.showLoading({mask: true})
          wx.$post(1,'Stock/delete_bom',{row_id: rid}).then(res=>{
            if (res.errcode != 0)return;

            let key,list = this.data.list;

            wx.$toast('删除成功！');

            //一级删除成功
            if (p_index === undefined){
              list.splice(s_index, 1);
              key = 'list'
            } else {
              list = list[p_index].children;
              list.splice(s_index, 1);
              key = `list[${p_index}].children`;
            }

            this.setData({ [key]: list });
          })

        }
      },
    })
  },

  //跳转页面
  navTo(e){
    let {type,p_index,p_val,s_index,s_val} = e.currentTarget.dataset,
      url = '';
    let obj = {type,p_index,p_val,s_index,s_val};

    if (['add_sub','add'].includes(type) && !this.checkAuth('tableAppend')) return;
    if (type === 'edit' && !this.checkAuth('tableEdit')) return;

    wx.setStorageSync('bomData',{type,p_index,p_val,s_index,s_val}) ;

    wx.navigateTo({
      url: '/stock/bom_update/bom_update'
    })
  },

  //获取数据
  getDataList(){
    let url = 'Stock/query_bom',
      {page,limit} = this.data,
      post = {"row_id": 0,page,limit};
    wx.$post(1,url,post).then(res => {

      let total = 0,
        list = this.data.list,
        sumArr = [],
        obj = {};
      if (res.data.row){
        total = res.data.total;
        let rows = res.data.row;
        if(page !== 1) rows = [ ...list,...rows, ];
        obj = {total,list: rows,page};
      }
      sumArr.push({name: '记录数',num: total});
      if (res.data.sum && res.data.sum[0]) {
        wx.$each(res.data.sum[0],(key,val)=>{
          sumArr.push({name: key,num: wx.$util.formatNum(val)});
        })
      }
      obj.sumList = sumArr;
      this.setData(obj);

    });
  },


  //获取明细数据
  getDetailData(pid,index){
    this.getData('Stock/query_bom_detailed',{row_id: pid}).then(data=>{
      let { list } = this.data,
        item = list[index];
      item.children = data;
      item.is_open = true;
      item.is_loaded = true;
      this.setData({ [`list[${index}]`]: item });
    });
  },

  getData(url,post){
    return new Promise(resolve => {
      wx.$post(1,url,post).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        resolve(data);
      })
    });

  },

  //刷新
  refreshData(rid,s_index,pid,p_index){
    if (!rid){
      //一级新增
      if ([undefined,null].includes(p_index)){
        this.getFirstPage();
        return
      }
      //二级新增
      this.getDetailData(pid,p_index);
      return
    }
    let url = '',
      post = {},
      key = '',
      obj = '';
    //一级编辑
    if ([undefined,null].includes(p_index)) {
      url = 'Stock/query_bom';
      post = {"row_id": rid,"page": 1,"limit": 1};
      key = `list[${s_index}]`;
      let {is_loaded,is_open,children} = this.data.list[s_index];
      obj = {is_loaded, is_open, children}

    }else { //二级编辑
      url = 'Stock/query_bom_detailed';
      post = {"row_id": pid};
      key = `list[${p_index}].children[${s_index}]`
    }
    this.getData(url,post).then(res=>{
      let data = res[0];
      obj && (data = {...data,...obj});
      this.setData({[key]: data});
    });

  },

  checkAuth(type){
    let flag = false,
      obj = {
        tableAppend: '抱歉，您没有权限新增该模块数据！',
        tableEdit: '抱歉，您没有权限编辑该模块数据！',
        tableDelete: '抱歉，您没有权限删除该模块数据！',
      };
    flag = this.data.auth[type];
    if (!flag){
      wx.$toast(obj[type]);
    }
    return flag;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    wx.$getAuth('bom').then(res=>{
      if (!res.tableSee) {
        wx.$toast('抱歉，您没有权限查看该模块数据！',1000).then(()=>{
          wx.navigateBack({ delta:1 });
        });
        return
      }
      this.setData({
        auth: res
      });
      this.getDataList();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
